package com.system.brandsserver.controller;


import com.system.brandsserver.common.Constant;
import com.system.brandsserver.common.ResultData;
import com.system.commonutils.pojo.FileBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@RestController
@Api(value = "上传图片",tags = "上传图片")
public class UploadPhotoController {
    @RequestMapping(value = "upload.do" ,method = RequestMethod.POST )
    @ApiOperation(value = "上传图片", notes = "上传图片", httpMethod = "post", response = ResultData.class)

    public ResultData addBrand(@Validated FileBean fileBean, HttpServletRequest request) throws IOException {
        System.out.println("方法：addEmp===========================" + fileBean);
        System.out.println(fileBean.getFile());
        MultipartFile upload = fileBean.getFile();
        ResultData resultData = new ResultData();
        System.out.println("====fileupload方法=====");
        String path = request.getSession().getServletContext().getRealPath("/uploads");
        System.out.println(path);
        //创建文件夹并判断文件夹是否存在
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        System.out.println("文件上传成功111111");
        //获取上传文件名称（包括后缀名，tupian.jsp）
        String filename = upload.getOriginalFilename();
        System.out.println(filename);
        //把文件名称设置为唯一值
        String uuid = UUID.randomUUID().toString().replace("_", "");
        //完成文件上传
        upload.transferTo(new File(path, uuid + filename));
        System.out.println("文件上传成功222222");
//        http://101.133.208.20:8080
        String a = "http://101.133.208.20:8080"+"/uploads/"+uuid+filename;
        List<String> list = new ArrayList<>();
        list.add(a);
        System.out.println(a);
        if(upload!=null){
            resultData.setCode(Constant.CODE_STATUS_SUCCESS);
            resultData.setMessage("上传成功");
            resultData.setData(list);
            return resultData;
        }else {
            resultData.setCode(Constant.CODE_STATUS_FAILURE);
            resultData.setMessage("上传失败");
            return resultData;
        }
    }
}